/**
 * Class: PowerDisplay
 *
 * Purpose: 
 *
 * Created: Feb 17, 2010 @ 11:49:55 AM
 * @author Ken Scott
 */
package org.openfantasia.songanalyst.controls;

import org.openfantasia.util.listener.Event;
import org.openfantasia.util.listener.FloatArray;
import org.openfantasia.util.listener.Listener;
import org.openfantasia.util.math.Math1D;
import org.openfantasia.util.math.PMath;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.*;

public class PowerDisplay extends JComponent implements Listener {

	private float scale;

	private float[] values;

	private float avg;

	private float rms;

	private float minFreq, maxFreq;

	private Color curveC;

	private Color avgC;

	private Color rmsC;


	public PowerDisplay(float scale, Color curveC, Color avgC, Color rmsC) {
		this.scale = scale;
		this.curveC = curveC;
		this.avgC = avgC;
		this.rmsC = rmsC;
		setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
	}


	public void receive(Event event) {
		values = ((FloatArray) event).getValue();
		values = Math1D.scale(scale, values);
		avg = Math1D.avg(values);
		rms = avg * (float) PMath.SQRT2_2;
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				draw(PowerDisplay.this.getGraphics());
			}
		});
	}


	public void draw(Graphics g) {
		Rectangle bounds = getBounds();
		Shape clip = g.getClip();
		g.clipRect(bounds.x, bounds.y, bounds.width, bounds.height);
		int width = bounds.width;
		int height = bounds.height;

		g.setColor(Color.BLACK);
		g.fillRect(0, 0, bounds.width, bounds.height);

		if (values != null) {
			g.setColor(curveC);
			float px = bounds.x, py = bounds.y + height, nx, ny;
			for (int i = 0; i < values.length; i++) {
				float di = (float) i / (float) values.length;
				nx = bounds.x + width * di;
				ny = bounds.y + height - ((float) i * values[i] / 40f);
				g.drawLine((int) px, (int) py, (int) nx, (int) ny);
				px = nx;
				py = ny;
			}
		}

		g.setClip(clip);
	}


	public void paint(Graphics g) {
		super.paint(g);
		draw(g);
	}
}
